package com.example.ks.servlet;

import com.example.ks.dao.OrderDao;
import com.example.ks.dao.UserDao;
import com.example.ks.dao.impl.OrderDaoImpl;
import com.example.ks.dao.impl.UserDaoImpl;
import com.example.ks.entity.Order;
import com.example.ks.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user-my-order")
public class UserMyOrderServlet extends HttpServlet {
    private OrderDao orderDao;
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        super.init();
        orderDao = new OrderDaoImpl();
        userDao = new UserDaoImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        if (currentUser == null) {
            request.setAttribute("error", "请先登录再查看订单");
            request.getRequestDispatcher("login-register.jsp").forward(request, response);
            return;
        }

        try {
            // 获取用户订单
            List<Order> orders = orderDao.getOrdersByUserId(currentUser.getId());

            // 构建用户ID到用户名的映射
            Map<Integer, String> userNames = new HashMap<>();
            userNames.put(currentUser.getId(), currentUser.getUsername());

            // 收集所有订单涉及的管理员ID
            for (Order order : orders) {
                int adminId = order.getAdminId();
                if (!userNames.containsKey(adminId)) {
                    User admin = userDao.findById(adminId);
                    if (admin != null) {
                        userNames.put(adminId, admin.getUsername());
                    } else {
                        userNames.put(adminId, "未知管理员");
                    }
                }
            }

            // 设置订单相关数据和action标记
            request.setAttribute("orders", orders);
            request.setAttribute("userNames", userNames);
            request.setAttribute("action", "orders"); // 关键修复点

            // 添加日志帮助调试
            System.out.println("Fetching orders for user: " + currentUser.getId());
            System.out.println("Found " + orders.size() + " orders");

            request.getRequestDispatcher("user-index.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "获取订单信息失败: " + e.getMessage());
            request.getRequestDispatcher("user-index.jsp").forward(request, response);
        }
    }
}